package servlet;

import com.alibaba.fastjson.JSON;
import entity.Flower;
import service.Impl.flowerServiceImpl;
import service.flowerService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet(urlPatterns = "/flowerServlet")
public class flowerServlet extends HttpServlet{
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        PrintWriter out =resp.getWriter();
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        flowerService flowerService=new flowerServiceImpl();
        List<Flower> listAll=flowerService.select();
        String opr=req.getParameter("opr");
        String path=req.getContextPath();
        String neirong=JSON.toJSONString(listAll);
        System.out.println(neirong);
        out.print(neirong);

        if ("add".equals(opr)){
            String name=req.getParameter("name");
            String bieming=req.getParameter("bieming");
            String keshu=req.getParameter("keshu");
            double price=Double.parseDouble(req.getParameter("price"));
            String address=req.getParameter("address");
            int hangshu=flowerService.add(name,bieming,keshu,price,address);
            if (name==null){
                out.print("<script>alert('请填写完整信息')</script>");
                return;
            }else if (bieming==null){
                out.print("<script>alert('请填写完整信息')</script>");
                return;
            }else if (keshu==null){
                out.print("<script>alert('请填写完整信息')</script>");
                return;
            }else if (price==0){
                out.print("<script>alert('请填写完整信息')</script>");
                return;
            }else if (address==null){
                out.print("<script>alert('请填写完整信息')</script>");
                return;
            }
            else {

            if (hangshu>0){
                out.print("<script>alert('添加成功!');location.href='"+path+"/index.jsp?opr=select'</script>");
            }

            }

        }

    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }
}
